/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package login;

import properties.ProjResouces;
import com.ibatis.sqlmap.client.SqlMapClient;
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import resources.captcha.CaptchaEngine;
import utils.LoginUtils;
import java.util.Date;

/**
 *
 * @author TECHNOLOGIES
 */
public class LoginScreen extends javax.swing.JFrame {

    /**
     * Creates new form LoginScreen
     */
    int captchaNum1 = 0;
    int captchaNum2 = 0;
    int captchaVar = 0;
    int count = 3;
    int intCaptchaAns = 0;
    SqlMapClient smc = null;
    
    String userName = null;
    String password = null;
    int accountFlag = 0;
    String currTime =  null;
    
    public LoginScreen() 
    {
        initComponents();
        this.callCaptcha(1);
        currTime =  new Date().toString();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelProjName = new javax.swing.JLabel();
        labelLoginImg = new javax.swing.JLabel();
        labelLoginLabel = new javax.swing.JLabel();
        labelUserName = new javax.swing.JLabel();
        labelUserPassword = new javax.swing.JLabel();
        textUserName = new javax.swing.JTextField();
        textPassword = new javax.swing.JPasswordField();
        labelCaptchaNote = new javax.swing.JLabel();
        labelWarning = new javax.swing.JLabel();
        labelCaptcha = new javax.swing.JLabel();
        textCaptchaAns = new javax.swing.JTextField();
        buttonSubmit = new javax.swing.JButton();
        labelLoginBG = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login Screen - College Accounts");
        setAlwaysOnTop(true);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setFocusCycleRoot(false);
        setLocationByPlatform(true);
        setName("loginFrame"); // NOI18N
        setUndecorated(true);
        setResizable(false);
        getContentPane().setLayout(null);

        labelProjName.setFont(new java.awt.Font("Courier New", 1, 36)); // NOI18N
        labelProjName.setForeground(new java.awt.Color(255, 255, 255));
        labelProjName.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelProjName.setText("College Accountant");
        getContentPane().add(labelProjName);
        labelProjName.setBounds(180, 20, 420, 40);
        labelProjName.getAccessibleContext().setAccessibleName("labelProjName");

        labelLoginImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/user_256.png"))); // NOI18N
        getContentPane().add(labelLoginImg);
        labelLoginImg.setBounds(260, 90, 270, 220);

        labelLoginLabel.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
        labelLoginLabel.setForeground(new java.awt.Color(255, 255, 255));
        labelLoginLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelLoginLabel.setText("Sign-in");
        labelLoginLabel.setToolTipText("Sign-in");
        getContentPane().add(labelLoginLabel);
        labelLoginLabel.setBounds(270, 330, 240, 30);

        labelUserName.setFont(new java.awt.Font("Courier New", 0, 18)); // NOI18N
        labelUserName.setForeground(new java.awt.Color(255, 255, 255));
        labelUserName.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelUserName.setText("User Name :");
        getContentPane().add(labelUserName);
        labelUserName.setBounds(200, 390, 130, 20);

        labelUserPassword.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
        labelUserPassword.setForeground(new java.awt.Color(255, 255, 255));
        labelUserPassword.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelUserPassword.setText("Please solve the puzzle");
        getContentPane().add(labelUserPassword);
        labelUserPassword.setBounds(210, 450, 350, 20);

        textUserName.setFont(new java.awt.Font("Courier New", 0, 14)); // NOI18N
        textUserName.setToolTipText("Enter User Name");
        getContentPane().add(textUserName);
        textUserName.setBounds(360, 390, 200, 20);

        textPassword.setToolTipText("Enter Password");
        getContentPane().add(textPassword);
        textPassword.setBounds(360, 420, 200, 20);

        labelCaptchaNote.setFont(new java.awt.Font("Courier New", 0, 18)); // NOI18N
        labelCaptchaNote.setForeground(new java.awt.Color(255, 255, 255));
        labelCaptchaNote.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelCaptchaNote.setText("Password  :");
        getContentPane().add(labelCaptchaNote);
        labelCaptchaNote.setBounds(200, 420, 130, 20);

        labelWarning.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N
        labelWarning.setForeground(new java.awt.Color(255, 204, 51));
        labelWarning.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        getContentPane().add(labelWarning);
        labelWarning.setBounds(100, 360, 590, 20);

        labelCaptcha.setFont(new java.awt.Font("Courier New", 0, 18)); // NOI18N
        labelCaptcha.setForeground(new java.awt.Color(255, 255, 255));
        labelCaptcha.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        getContentPane().add(labelCaptcha);
        labelCaptcha.setBounds(260, 480, 120, 20);

        textCaptchaAns.setFont(new java.awt.Font("Courier New", 0, 18)); // NOI18N
        textCaptchaAns.setToolTipText("Please enter the result");
        getContentPane().add(textCaptchaAns);
        textCaptchaAns.setBounds(400, 480, 110, 20);

        buttonSubmit.setText("Submit");
        buttonSubmit.setToolTipText("Click to Submit");
        buttonSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSubmitActionPerformed(evt);
            }
        });
        getContentPane().add(buttonSubmit);
        buttonSubmit.setBounds(360, 510, 75, 23);

        labelLoginBG.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/loginbg.jpg"))); // NOI18N
        labelLoginBG.setToolTipText("Login Screen - College Accounts");
        labelLoginBG.setName(""); // NOI18N
        getContentPane().add(labelLoginBG);
        labelLoginBG.setBounds(0, 0, 810, 630);

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSubmitActionPerformed
        try
        {
            System.out.println("Path came: "+ProjResouces.LOGIN_LOG_PATH);
            FileOutputStream f = new FileOutputStream(ProjResouces.LOGIN_LOG_PATH);
            System.setErr(new PrintStream(f));
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
        ArrayList<String> loginInfo = new ArrayList<String>();
        System.err.println( new Date().toString()+":LoginScreen: "+"Size of LoginInfo: "+ (LoginUtils.getLoginInfo(textUserName.getText().trim())).size());
        if((LoginUtils.getLoginInfo(textUserName.getText().trim())).size()>0)
        {
            loginInfo = LoginUtils.getLoginInfo(textUserName.getText().trim());
            userName = loginInfo.get(0);
            System.err.println( new Date().toString()+":LoginScreen: "+"userName: "+userName);
            password = loginInfo.get(1);
            System.err.println( new Date().toString()+":LoginScreen: "+"password: "+password);
            accountFlag = Integer.parseInt(loginInfo.get(2));
            System.err.println( new Date().toString()+":LoginScreen: "+"accountFlag: "+accountFlag);
        }
        else
        {
            labelWarning.setText("Account cannot be found.");
        }
        if(accountFlag == 0)
        {
            if(textUserName.getText().trim().length()>0 && textPassword.getPassword().length>0 && textCaptchaAns.getText().trim().length()>0)
            {
                if(textUserName.getText().equalsIgnoreCase(userName) && textPassword.getText().equalsIgnoreCase(password))
                {
                    try
                    {  
                        if(textCaptchaAns.getText().trim().length()>0)
                        {
                            intCaptchaAns = Integer.parseInt(textCaptchaAns.getText());
                            if((intCaptchaAns!=captchaVar))
                            {
                                this.callCaptcha(2);
                            }
                            else
                            {
                                mainscreen.FrameMainMenu mainScreen = new mainscreen.FrameMainMenu();
                                mainScreen.setSize(600, 400);
                                mainScreen.setVisible(true);
                                this.dispose();
                            }
                        }
                    }
                    catch(NumberFormatException e)
                    {
                       this.callCaptcha(4);
                    }

                }
                else
                {
                    if(count!=1)
                    {
                        count--;
                        labelWarning.setText("You have Entered wrong password. You have "+count+" tries left.");
                        this.callCaptcha(3);
                    }
                    else
                    {
                        labelWarning.setText("Your account has been De-Activated.");

                    }
                }
            }
            else
            {
                if((textUserName.getText().trim().length()==0) && (textPassword.getPassword().length==0) && (textCaptchaAns.getText().trim().length()==0))
                {
                    textUserName.setBackground(Color.red);
                    textPassword.setBackground(Color.red);
                    textCaptchaAns.setBackground(Color.red);
                    labelWarning.setText("Please fill the details below.");
                }
                else if((textUserName.getText().trim().length()==0))
                {
                    textUserName.setBackground(Color.white);
                    textPassword.setBackground(Color.white);
                    textCaptchaAns.setBackground(Color.white);
                    labelWarning.setText("Please enter User Name.");
                }
                else if((textPassword.getPassword().length==0))
                {
                    textUserName.setBackground(Color.white);
                    textPassword.setBackground(Color.red);
                    textCaptchaAns.setBackground(Color.white);
                    labelWarning.setText("Please enter Password.");
                }
                else if((textCaptchaAns.getText().trim().length()==0))
                {
                    textUserName.setBackground(Color.white);
                    textPassword.setBackground(Color.white);
                    textCaptchaAns.setBackground(Color.red);
                    labelWarning.setText("Please solve the puzzle.");
                }
            }
        }
        else
        {
            labelWarning.setText("Your account is already Desabled.");
        }
    }//GEN-LAST:event_buttonSubmitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginScreen().setVisible(true);
            }
        });
        
    }
        

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonSubmit;
    private javax.swing.JLabel labelCaptcha;
    private javax.swing.JLabel labelCaptchaNote;
    private javax.swing.JLabel labelLoginBG;
    private javax.swing.JLabel labelLoginImg;
    private javax.swing.JLabel labelLoginLabel;
    private javax.swing.JLabel labelProjName;
    private javax.swing.JLabel labelUserName;
    private javax.swing.JLabel labelUserPassword;
    private javax.swing.JLabel labelWarning;
    private javax.swing.JTextField textCaptchaAns;
    private javax.swing.JPasswordField textPassword;
    private javax.swing.JTextField textUserName;
    // End of variables declaration//GEN-END:variables

    public void callCaptcha(int intType)
    {
        if(intType==1)
        {
            labelWarning.setText("Please fill the details below.");
            captchaNum1 = CaptchaEngine.randIntOne(1, 99);
            captchaNum2 = CaptchaEngine.randIntTwo(1, 99);
            captchaVar = captchaNum1+captchaNum2;
            labelCaptcha.setText(captchaNum1+" + "+captchaNum2+" = ");
        }
        if(intType==2)
        {
            labelWarning.setText("Please solve the puzzle again.");
            textUserName.setBackground(Color.white);
            textPassword.setBackground(Color.white);
            textCaptchaAns.setBackground(Color.red);
            textCaptchaAns.setText("");
            captchaNum1 = CaptchaEngine.randIntOne(1, 99);
            captchaNum2 = CaptchaEngine.randIntTwo(1, 99);
            captchaVar = captchaNum1+captchaNum2;
            labelCaptcha.setText(captchaNum1+" + "+captchaNum2+" = ");
        }
        if(intType==3)
        {
            textUserName.setBackground(Color.white);
            textCaptchaAns.setBackground(Color.white);
            textPassword.setBackground(Color.red);
            textPassword.setText("");
            textCaptchaAns.setText("");
            captchaNum1 = CaptchaEngine.randIntOne(1, 99);
            captchaNum2 = CaptchaEngine.randIntTwo(1, 99);
            captchaVar = captchaNum1+captchaNum2;
            labelCaptcha.setText(captchaNum1+" + "+captchaNum2+" = ");
        }
        if(intType==4)
        {
            textUserName.setBackground(Color.white);
            textPassword.setBackground(Color.white);
            textCaptchaAns.setBackground(Color.red);
            textCaptchaAns.setText("");
            labelWarning.setText("Please use number in Puzzle answer.");
            captchaNum1 = CaptchaEngine.randIntOne(1, 100);
            captchaNum2 = CaptchaEngine.randIntTwo(1, 100);
            captchaVar = captchaNum1+captchaNum2;
            labelCaptcha.setText(captchaNum1+" + "+captchaNum2+" = ");
        }
    }
}
